<template>
	<view class="chating-wrapper" @click.stop="chatingWrapperClick">
		<!-- 视频全屏播放区 -->
		<view v-if="isVideoFullScreen" style="position:fixed;top:0;bottom:0;right:0;left:0;z-index:999;background-color:#000;">
			<video id="videoEle" :src="videoSrc" @ended="videoEnded" :show-fullscreen-btn="false" controls style="width:100%;height:100%;"></video>
		</view>
		
		<!-- 消息记录 -->
		<view class="record-wrapper" id="recordWrapper">
			<view v-for="(message, index) in messageArr" :key="index">
				<view class="record-item-time-wrapper" v-if="message.displayTimeHeader != ''">
					<text class="record-item-time">{{ message.displayTimeHeader }}</text>
				</view>
				<view
					v-if="message.sendOrReceive == 'send'"
					:class="message.sendOrReceive == 'send' ? 'record-chatting-item self' : ''"
					:style="'justify-content: ' + message.type === 'tip' || message.type === 'notification' ? 'center' : 'flex-end'"
					@longpress="showEditorMenu(message)"
				>
					<view v-if="message.type === 'video'" @click.stop="requestFullScreenVideo(message.video)" class="small-video-wrapper">
						<view class="video-triangle"></view>
						<view style="color: #000;">{{ message.video.videoSecond }}</view>
					</view>
					<view v-if="message.type === 'audio'" class="audio-wrapper" @click.stop="playAudio(message.audio)" style="background-color:#3387FF;color: #000;">
						<image :src="iconBase64Map.iconVoiceWhite" class="image"></image>
						<text class="text">{{ message.audio.second }}</text>
					</view>
					<rich-text v-if="message.type === 'image'" class="record-chatting-item-text nobg" :nodes="message.nodes"></rich-text>
					<rich-text v-if="message.type === '贴图表情'" class="record-chatting-item-text nobg" :nodes="message.nodes"></rich-text>
					<rich-text
						v-if="message.type === 'text' || message.type === 'file' || message.type === 'robot'"
						class="record-chatting-item-text"
						:nodes="message.nodes"
					></rich-text>
					<rich-text v-if="message.type === 'tip' || message.type === 'notification'" class="tip-rich-text" :nodes="message.nodes"></rich-text>
					<text
						v-if="
							message.type !== 'tip' &&
								message.type !== 'notification' &&
								message.type !== 'image' &&
								message.type !== 'video' &&
								message.type !== '贴图表情' &&
								message.type !== '患者信息' &&
								message.type !== '处方信息'
						"
						class="right-triangle"
					></text>
		
					<view class="striveOrders-recipe" v-if="message.type === '处方信息'">
						<view class="outer9">
							<image src="http://k8s.vendingtech.vip/images/order_icon@2x.png" class="label3"></image>
							<view lines="1" class="txt3">电子处方</view>
						</view>
						<view class="outer10">
							<view lines="1" class="info1">诊断：{{ message.text.diagnose }}</view>
							<view class="outer11" @click="gotoRouter2('/pages-doctor/prescInfo/prescInfo?id=' + message.text.id + '&role=' + role,message.text.id)">查看处方</view>
						</view>
					</view>
		
					<image
						v-if="message.type !== 'tip' && message.type !== 'notification' && role == 0 && message.type !== '患者信息'"
						:src="userInfo.avatar"
						class="record-chatting-item-img"
					></image>
		
					<image
						v-if="message.type !== 'tip' && message.type !== 'notification' && role == 1 && message.type !== '患者信息'"
						:src="doctorInfo.picture"
						class="record-chatting-item-img"
					></image>
				</view>
				<view
					v-if="message.sendOrReceive == 'receive'"
					:class="message.sendOrReceive == 'receive' ? 'record-chatting-item other' : ''"
					:style="'justify-content: ' + message.type === 'tip' || message.type === 'notification' ? 'center' : 'flex-start'"
					@longpress="showEditorMenu(message)"
				>
					<!--
					<image
						v-if="message.type !== 'tip' && message.type !== 'notification' && message.type !== 'custom' && message.type !== '患者信息'"
						@click.stop="switchToPage(message.custom)"
						:data-account="message.from"
						:src="(personList[message.from] && personList[message.from].avatar) || defaultUserLogo"
						class="record-chatting-item-img"
					></image>
					-->
					<image
						v-if="message.type !== 'tip' && message.type !== 'notification' && message.type !== 'custom' && message.type !== '患者信息'"
						@click.stop="switchToPage(message.custom)"
						:data-account="message.from"
						:src="currentAvatar"
						class="record-chatting-item-img"
					></image>
					<text
						v-if="
							message.type !== 'tip' &&
								message.type !== 'notification' &&
								message.type !== 'image' &&
								message.type !== 'video' &&
								message.type !== '贴图表情' &&
								message.type !== '患者信息' &&
								message.type !== '处方信息'
						"
						class="left-triangle"
					></text>
		
					<view v-if="message.type === 'video'" @click.stop="requestFullScreenVideo(message.video)" class="small-video-wrapper">
						<view class="video-triangle"></view>
						<view style="color: #000;">{{ message.video.videoSecond }}</view>
					</view>
					<view v-if="message.type === 'audio'" @click.stop="playAudio(message.audio)" class="audio-wrapper">
						<image :src="iconBase64Map.iconVoiceGrey" class="image"></image>
						<text class="text" style="color:#000;">{{ message.audio.second }}''</text>
					</view>
					<rich-text v-if="message.type === 'image'" class="record-chatting-item-text nobg" :nodes="message.nodes"></rich-text>
					<rich-text v-if="message.type === '贴图表情'" class="record-chatting-item-text nobg" :nodes="message.nodes"></rich-text>
					<rich-text
						v-if="message.type === 'text' || message.type === 'file' || message.type === 'robot' || message.type === 'custom'"
						class="record-chatting-item-text"
						style="color:#000;background-color:#fff;"
						:nodes="message.nodes"
					></rich-text>
					<rich-text v-if="message.type === 'tip' || message.type === 'notification'" class="tip-rich-text" :nodes="message.nodes"></rich-text>
		
					<view class="striveOrders-recipe" v-if="message.type === '处方信息'">
						<view class="outer9">
							<image src="http://k8s.vendingtech.vip/images/order_icon@2x.png" class="label3"></image>
							<view lines="1" class="txt3">电子处方</view>
						</view>
						<view class="outer10">
							<view lines="1" class="info1">诊断：{{ message.text.diagnose }}</view>
							<view class="outer11" @click="gotoRouter2('/pages-doctor/prescInfo/prescInfo?id=' + message.text.id + '&role=' + role,message.text.id)">查看处方</view>
						</view>
					</view>
				</view>
		
				<view class="striveOrders-userInfo" v-if="message.type === '患者信息'" @click="switchToOrderInfo(message.custom)">
					<!-- <view class="striveOrders-drug" v-if="message.text.commodityOrder.orderType == 2 && message.text.questionOrder.drugQuestionReq">
						<u-title value="已选药品"></u-title>
						<view class="striveOrders-drug-list">
							<u-show-goods v-for="(item, indexs) in message.text.questionOrder.drugQuestionReq.commodityList" :key="indexs" :data="item"></u-show-goods>
						</view>
					</view> -->
		
					<view class="striveOrders-patient">
						<u-title value="问诊信息"></u-title>
						<view class="striveOrders-patient-box">
							<view class="striveOrders-patient-outer">
								<text lines="1" class="word9">患者信息：</text>
								<text lines="1" class="word10">
									{{ message.text.patient.patientName }}&nbsp;&nbsp;{{ rangeSex[message.text.patient.sex].text }}&nbsp;&nbsp;{{ message.text.patient.phone }}
								</text>
							</view>
							<view class="striveOrders-patient-outer" v-if="message.text.commodityOrder.orderType == 2">
								<text lines="1" class="word9">所患疾病：</text>
								<text lines="1" class="word10">{{ message.text.questionOrder.content }}</text>
							</view>
		
							<view class="striveOrders-patient-outer" v-if="message.text.commodityOrder.orderType == 2">
								<text lines="1" class="word9">肝功能：</text>
								<text lines="1" class="word10">{{ functionList[message.text.questionOrder.drugQuestionReq.liver].name }}</text>
							</view>
		
							<view class="striveOrders-patient-outer" v-if="message.text.commodityOrder.orderType == 2">
								<text lines="1" class="word9">肾功能：</text>
								<text lines="1" class="word10">{{ functionList[message.text.questionOrder.drugQuestionReq.kidney].name }}</text>
							</view>
		
							<view class="striveOrders-patient-outer" v-if="message.text.commodityOrder.orderType == 2 && message.text.questionOrder.drugQuestionReq.allergy == 1">
								<text lines="1" class="word9">过敏史：</text>
								<text lines="1" class="word10">{{ message.text.questionOrder.drugQuestionReq.allergyText }}</text>
							</view>
		
							<view class="striveOrders-patient-outer" v-if="message.text.commodityOrder.orderType == 2">
								<text lines="1" class="word9">生育状态及计划：</text>
								<text lines="1" class="word10">{{ birthStatusList[message.text.questionOrder.drugQuestionReq.birthStatus].name }}</text>
							</view>
		
							<view class="striveOrders-patient-outer" v-if="message.text.commodityOrder.orderType != 2">
								<text lines="1" class="word9">患病时间：</text>
								<text lines="1" class="word10">{{ durationList[message.text.questionOrder.duration].name }}</text>
							</view>
							<view class="striveOrders-patient-outer" v-if="message.text.commodityOrder.orderType != 2">
								<text lines="1" class="word9">就诊情况：</text>
								<text lines="1" class="word10">{{ isLookHospList[message.text.questionOrder.isLookHosp].name }}</text>
							</view>
							<view class="striveOrders-patient-outer" v-if="message.text.commodityOrder.orderType != 2">
								<text lines="1" class="word9">病情描述：</text>
								<text lines="1" class="word10">{{ message.text.questionOrder.content }}</text>
							</view>
						</view>
					</view>
		
					<view class="striveOrders-report" v-if="message.text.questionOrder.reportList && message.text.questionOrder.reportList.length > 0">
						<u-title value="图片"></u-title>
						<view class="striveOrders-report-list">
							<image :src="item" class="striveOrders-report-item" v-for="(item, indexs) in message.text.questionOrder.reportList" :key="indexs"></image>
						</view>
					</view>
					
					<!-- <view class="striveOrders-report" v-if="message.text.questionOrder.reexamination">
						<u-title value="PDF文件"></u-title>
						<view class="striveOrders-report-list">{{message.text.questionOrder.reexamination.split('/').pop()}}</view>
					</view> -->
				</view>
			</view>
		</view>
		
		<view class="chatRoom-end" v-if="messageArr.length > 0 && inquiryStatus == 3">本次问诊已结束</view>
		
		<!--底部输入框  -->
		<view
			v-if="chatType === 'p2p' && inquiryStatus != 3"
			class="chatinput-wrapper iphonex-footer"
			:style="'margin-bottom: ' + focusFlag ? 20 : 0 + 'rpx'"
			@click.stop="stopEventPropagation"
		>
			<view class="chatinput-content">
				<image
				v-if="sendType == 0"
					src="https://cdn.yingpaipay.com/20250811151308_148.png"
					class="chatinput-img"
					@click.stop="switchSendType"
				></image>
				<image
				v-else
					src="https://cdn.yingpaipay.com/20250811151322_150.png"
					class="chatinput-img"
					@click.stop="switchSendType"
				></image>
				<input
					style="margin-bottom: 20rpx;"
					v-if="sendType == 0"
					:value="inputValue"
					:focus="focusFlag"
					@input="inputChange"
					@focus="inputFocus"
					@blur="inputBlur"
					@confirm="inputSend"
					class="chatinput-input"
					confirm-type="send"
				/>
				<!-- <button v-if="sendType == 1" class=" isLongPress ? 'chatinput-voice-mask chatinput-voice-mask-hover' : 'chatinput-voice-mask' " hover-class="none" catchtouchstart='longPressStart' catchlongpress='voiceBtnLongTap' catchtouchend='longPressEnd'>按住说话</button> -->
				<button
					v-if="sendType == 1"
					class=" isLongPress ? 'chatinput-voice-mask chatinput-voice-mask-hover' : 'chatinput-voice-mask' "
					hover-class="none"
					@touchstart.stop="longPressStart"
					@touchend.stop="longPressEnd"
				>
					{{ isLongPress ? '松开结束' : '按住说话' }}
				</button>
				<image src="https://cdn.yingpaipay.com/20250811151326_151.png" @click.stop="toggleMore" class="chatinput-img fr"></image>
				<image src="https://cdn.yingpaipay.com/20250811151319_149.png" @click.stop="toggleEmoji" class="chatinput-img fr emoji"></image>
			</view>
			<view v-if="emojiFlag" class="chatinput-subcontent"><u-emoji @EmojiClick="emojiCLick" @EmojiSend="emojiSend"></u-emoji></view>
			<view v-if="moreFlag" class="more-subcontent">
				<view class="more-subcontent-list">
					<view class="more-subcontent-item" @click.stop="chooseImageToSend">
						<image src="http://k8s.vendingtech.vip//images/photo.png" class="image"></image>
						<text class="text">相册</text>
					</view>
					<view class="more-subcontent-item" @click.stop="chooseImageOrVideo">
						<image src="http://k8s.vendingtech.vip/images/shoot.png" class="image"></image>
						<text class="text">拍摄</text>
					</view>
		
					<!--
					<view class="more-subcontent-item" @click.stop="gotoRouter('/pages-txy-im/videoCall2/videoCall2?userID=' + chatTo)" v-if="inquiryType == 1">
						<image src="http://k8s.vendingtech.vip/images/location.png" class="image"></image>
						<text class="text">视频通话</text>
					</view>
					-->
					<view class="more-subcontent-item" @click.stop="videoCalling" v-if="inquiryType == 1">
						<image src="http://k8s.vendingtech.vip/images/location.png" class="image"></image>
						<text class="text">视频通话</text>
					</view>
		
					<view class="more-subcontent-item" v-if="role == 1" @click.stop="goPharmacy">
						<image src="http://k8s.vendingtech.vip/images/morra.png" class="image"></image>
						<text class="text">开处方</text>
					</view>
		
					<view class="more-subcontent-item" v-if="role == 1" @click.stop="manualUpdateQuestionStatus">
						<image src="http://k8s.vendingtech.vip/images/morra.png" class="image"></image>
						<text class="text">结束问诊</text>
					</view>

					<view class="more-subcontent-item" v-if="role == 1" @click.stop="gotoRouter('/pages-doctor/cases/edit?params=' + JSON.stringify(casesNeedInfo))">
						<image src="http://k8s.vendingtech.vip/images/morra.png" class="image"></image>
						<text class="text">写病历</text>
					</view>
					
					<view class="more-subcontent-item" v-if="role == 1" @click.stop="gotoRouter('/pages-doctor/cases/list?params=' + JSON.stringify(patientNeesInfo))">
						<image src="http://k8s.vendingtech.vip/images/morra.png" class="image"></image>
						<text class="text">病历夹</text>
					</view>
		
					<view class="more-subcontent-item">
						<view class="image" style="background-color: transparent;"></view>
						<text class="text"></text>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 腾讯IM视频通话组件 -->
		<view>
			<tuicalling ref="TUICalling" id="TUICalling-component" :config="tuiCallingConfig"></tuicalling>
		</view>

	</view>
</template>

<script>
import { generateBigEmojiImageFile, generateRichTextNode, generateImageNode, generateImageNodeTxy, calcTimeHeader } from '@/utils-im/util.js';
import dealGroupMsg from '@/utils-im/dealGroupMsg.js';
import * as iconBase64Map from '@/utils-im/imageBase64.js';
import uEmoji from '@/pages-txy-im/components/u-emoji/u-emoji.vue';
import { mapState, mapMutations, mapGetters } from 'vuex';
import { userInfo, imInfo, doctorInfo, currentImInfo } from '@/utils/token.js';
import { sdkAppId, apiUrl } from '@/config.js'
import { token } from '@/utils/token'
const app = getApp();
export default {
	components: {
		uEmoji
	},
	data() {
		return {
			videoContext: null, // 视频操纵对象
			isVideoFullScreen: false, // 视频全屏控制标准
			videoSrc: '', // 视频源
			recorderManager: null, // 微信录音管理对象
			recordClicked: false, // 判断手指是否触摸录音按钮
			iconBase64Map: {}, //发送栏base64图标集合
			isLongPress: false, // 录音按钮是否正在长按
			
			chatTo: '', //聊天对象account
			chatType: '', //聊天类型 advanced 高级群聊 normal 讨论组群聊 p2p 点对点聊天
			
			currentAvatar: '',
			
			focusFlag: false, //控制输入框失去焦点与否
			emojiFlag: false, //emoji键盘标志位
			moreFlag: false, // 更多功能标志
			sendType: 0, //发送消息类型，0 文本 1 语音
			messageArr: [], //[{text, time, sendOrReceive: 'send', displayTimeHeader, nodes: []},{type: 'geo',geo: {lat,lng,title}}]
			inputValue: '', //文本框输入内容
			from: '',
			showIndex: 10,
			userInfo: null,
			doctorInfo: null,
			endTime: new Date().getTime(), // 存储上次加载的最后一条消息的时间，后续加载更多使用
			accid: '', //对方聊天账号id
			role: 0, //当前聊天身份  0患者  1医生
			questionOrderId: null, //问诊id
			recipeId: null,
			custom: {}, //扩展字段
			orderInfo: null, //订单详情
			inquiryType: 0, //问诊类型  0图文  1视频
			inquiryStatus: 3, //问诊状态  0未结束  1已结束
			sendT: false, //首次发送问诊信息
			sendB: false, //结束问诊不发送问诊消息
			options: null,
			reLoad: new Function(),
			
			TUICalling: undefined,
			tuiCallingConfig: {
				sdkAppID: sdkAppId, // 开通实时音视频服务创建应用后分配的 SDKAppID
				userID: currentImInfo.get().id, // 用户 ID，可以由您的帐号系统指定
				userSig: currentImInfo.get().userSig, // 身份签名，相当于登录密码的作用
				type: 2 ,// 通话模式
				tim: getApp().globalData.tim
			},
			
			casesNeedInfo: {}, // 写病历需要的信息
			patientNeesInfo: {}, // 进入患者病历夹需要的信息
		};
	},
	watch: {
		rawMessageList() {
			this.getHistoryMsgs();
		},
		moreFlag(newValue) {}
	},
	computed: {
		...mapState({
			recipeInfo: state => state.recipeInfo
		}),
		...mapState('txyIm', {
			currentChatTo: 'currentChatTo',
			// currentChatInfo: 'currentChatInfo',
			rawMessageList: 'rawMessageList',
			defaultUserLogo: 'defaultUserLogo',
			// blackList: 'blackList',
			personList: 'personList',
			conversationRequestOrderIdDict: 'conversationRequestOrderIdDict'
		}),
		...mapGetters('txyIm', ['conversationAvatar'])
	},
	onLoad(options) {
		this.options = options;
		this.reLoad = (options, sendB) => {
			this.accid = options.accid ? options.accid : null;
			this.role = options.role ? options.role : 0;
			this.questionOrderId = options.questionOrderId ? options.questionOrderId : null;
			this.sendT = options.questionOrderId ? true : false;
			this.sendB = sendB;
			console.log(this.accid, this.role);
			
			this.$store.dispatch('txyIm/CurrentChatTo_Change', { session: 'C2C' + this.accid, account: this.accid });
			// 当前会话的所有消息设置已读
			app.globalData.tim.setMessageRead({conversationID: 'C2C' + this.accid});
			
			// 初始化聊天对象
			this.chatTo = this.accid;
			this.chatType = 'p2p';
			this.iconBase64Map = iconBase64Map;
			
			this.currentAvatar = this.conversationAvatar('C2C' + this.chatTo);
			
			this.tuiCallingConfig = {
				sdkAppID: sdkAppId, // 开通实时音视频服务创建应用后分配的 SDKAppID
				userID: currentImInfo.get().id, // 用户 ID，可以由您的帐号系统指定
				userSig: currentImInfo.get().userSig, // 身份签名，相当于登录密码的作用
				type: 2 ,// 通话模式
				tim: getApp().globalData.tim
			}
			// getApp().globalData.inVideoPhone = true;
			// 将初始化后到 TUICalling 实例注册到 this.TUICalling。
			this.TUICalling = this.$refs.TUICalling;
			// 初始化 TUICalling
			this.$nextTick(() => {
				this.TUICalling.init()
			})
			
			if (!this.rawMessageList || !this.rawMessageList.length || this.rawMessageList.length <= 0) {
				this.getHistoryMsgs();
			}
			
			if (this.role == 0) {
				this.userInfo = userInfo.get();
				
				// this.currentAvatar = this.userInfo.avatar;
				this.initMessage();
			} else {
				//医生需要先查询医生信息
				this.$api.getDoctorInfo({}).then(res => {
					if (res.code == 200) {
						this.doctorInfo = res.result;
						this.casesNeedInfo.doctorId = res.result.id
						this.casesNeedInfo.departmentName = res.result.departmentName
						// this.currentAvatar = this.doctorInfo.picture;
						this.initMessage();
					}
				});
			}
		}
		this.reLoad(options, true);
	},
	onShow() {
		uni.setKeepScreenOn({
			keepScreenOn: true
		});
		this.moreFlag = false;
		if (this.recipeInfo != null && this.role == 1) {
			//选择了处方，开始开方。调用开方接口和发送开方消息
			this.addUserRecipe();
		}
	},
	onReady() {
	},
	onUnload() {
		console.log('===============unload被调用了==================')
		// 回收 TUICalling
		this.TUICalling.destroyed()
		// getApp().globalData.inVideoPhone = false;
		/*
		getApp().globalData.tim.destroy().then(() => {
			this.initTxyIm(currentImInfo.get().sdkAppId, currentImInfo.get().id, currentImInfo.get().userSig);	
		})
		*/
		// 更新当前会话对象账户
		this.$store.dispatch('im/CurrentChatTo_Change', { session: '', account: '' });
	},
	methods: {
		...mapMutations({
			setRecipeInfo: 'setRecipeInfo'
		}),
		
		/**
		 * 获取云端历史记录
		 */
		getHistoryMsgs() {
			let messageList = [];
			let nextReqMessageID = null;
			let isCompleted = false;
			const fetchMessageList = () => {
				const params = {
					conversationID: 'C2C' + this.accid, 
					count: 15,
				};
				if (nextReqMessageID) {
					params['nextReqMessageID'] = nextReqMessageID;
				}
				app.globalData.tim.getMessageList(params).then(imResponse => {
					messageList = messageList.concat(imResponse.data.messageList); // 消息列表。
					nextReqMessageID = imResponse.data.nextReqMessageID; // 用于续拉，分页续拉时需传入该字段。
					isCompleted = imResponse.data.isCompleted; // 表示是否已经拉完所有消息。
					if (!isCompleted) {
						fetchMessageList();
					} else {
						messageList.sort((a, b) => (a.time - b.time))
						this.getHistoryMsgsDone(messageList);
						
						setTimeout(() => {
							this.scrollToBottom();
						}, 200);
					}
				});	
			}
			fetchMessageList()
		},
		/**
		 * 历史消息获取成功回调
		 */
		getHistoryMsgsDone(messageList) {
			let thisAccid;
			if (this.role == 0) {
				thisAccid = imInfo.get().id;
			} else {
				thisAccid = (this.doctorInfo && this.doctorInfo.id) || doctorInfo.get().id;
			}
		
			this.endTime = messageList && messageList[messageList.length - 1] && messageList[messageList.length - 1].time || new Date().getTime();
			this.messageArr = this.convertRawMessageListToRenderMessageArr(messageList);
			
			this.setMessage();
			// 重新计算所有时间
			this.reCalcAllMessageTime();
			// 隐藏loading动画
			uni.hideLoading();
		},
		
		convertRawMessageListToRenderMessageArr(messageList) {
			const TIM = app.globalData.TIM;
			const messageArr = [];
			const total = messageList.length;
			let idx = 0;
			for (const message of messageList) {
				idx++;
				let msgType = '';
				if (message.type === TIM.TYPES.MSG_CUSTOM) {
					const customMsgData = JSON.parse(message.payload.data);
					const customMsgType = customMsgData.type;
					if (customMsgType === 3) {
						msgType = '贴图表情';
					} else if (customMsgType === 100) {
						msgType = '患者信息';
						message.text = customMsgData.data;
					} else if (customMsgType === 101) {
						msgType = '处方信息';
						message.text = customMsgData.data;
					} else {
						msgType = 'IGNORE'
					}
					/*
					if (customMsgType === 1001 && message.to === currentImInfo.get().id && idx === total) {
						// 视频会话邀请
						uni.navigateTo({
							url: '/pages-txy-im/videoCall2/videoCall2?userID=' + this.chatTo + '&type=receiver'
						})
						break;
					}
					*/
				} else {
					msgType = message.type;
				}
				
				const time = message.time;
				const displayTimeHeader = this.judgeOverTwoMinute(time, messageArr);
				const sendOrReceive = message.flow === 'in' ? 'receive' : 'send';
				let specifiedObject = {};
				
				const custom = message.cloudCustomData ? JSON.parse(message.cloudCustomData) : {};
				
				switch (msgType) {
					case TIM.TYPES.MSG_TEXT: {
						specifiedObject = {
							nodes: generateRichTextNode(message.payload.text)
						};
						msgType = 'text';
						break;
					}
					case TIM.TYPES.MSG_IMAGE: {
						specifiedObject = {
							nodes: generateImageNodeTxy(message.payload.imageInfoArray)
						};
						msgType = 'image';
						break;
					}
					case TIM.TYPES.MSG_AUDIO: {
						specifiedObject = {
							audio: message.payload
						};
						msgType = 'audio';
						break;
					}
					case TIM.TYPES.MSG_VIDEO: {
						specifiedObject = {
							video: message.payload
						};
						msgType = 'video';
						break;
					}
					case '贴图表情': {
						const customMsgData = JSON.parse(message.payload.data);
						specifiedObject = {
							nodes: generateImageNode(generateBigEmojiImageFile(customMsgData))
						};
						break;
					}
					case TIM.TYPES.MSG_GRP_TIP: {
						specifiedObject = {
							text: message.payload.operationType,
							nodes: [
								{
									type: 'text',
									text: message.payload.operationType
								}
							]
						};
						msgType = 'tip';
						break;
					}
					case TIM.TYPES.MSG_FILE:
					case 'robot': {
						let text = msgType === TIM.TYPES.MSG_FILE ? '文件消息' : '机器人消息';
						specifiedObject = {
							nodes: [
								{
									type: 'text',
									text: `[${text}],请到手机或电脑客户端查看`
								}
							]
						};
						msgType = msgType === TIM.TYPES.MSG_FILE ? 'file' : 'robot';
						break;
					}
					case TIM.TYPES.MSG_CUSTOM: {
						specifiedObject = {
							nodes: [
								{
									type: 'text',
									text: '自定义消息'
								}
							]
						};
						msgType = 'custom';
						break;	
					}
					case TIM.TYPES.MSG_GRP_SYS_NOTICE: {
						specifiedObject = {
							// netbill的text为空
							text: message.payload.operationType,
							nodes: [
								{
									type: 'text',
									text: message.payload.operationType
								}
							]
						};
						msgType = 'notification';
						break;
					}
					default: {
						break;
					}
				}
				if (msgType !== 'IGNORE') {
					messageArr.push(
						Object.assign(
							{},
							{
								from: message.from,
								type: msgType,
								text: message.text || message.payload.data,
								time,
								custom: custom,
								sendOrReceive,
								displayTimeHeader,
								avatar: message.avatar
							},
							specifiedObject
						)
					);	
				}
			}
			return messageArr;
		},
		// 设置当前聊天数据
		setMessage() {
			//更新本地扩展字段
			console.log('当前聊天记录,处理后数据', this.messageArr);
			if (this.messageArr.length > 0) {
				this.custom = this.messageArr[this.messageArr.length - 1]?.custom;
			}
			if (!this.orderInfo && !this.questionOrderId) {
				this.questionOrderId = this.custom.questionOrderId;
		
				this.questionOrderDetail();
			}
			console.log('当前扩展字段', this.custom);
		},
		//订单详情
		questionOrderDetail() {
			console.log('订单详情Id', this.questionOrderId);
			this.$api
				.questionOrderDetail({
					params: {
						id: this.questionOrderId
					}
				})
				.then(res => {
					if (res.code == 200) {
						if (res.result) {
							console.log('订单详情', res.result);
							this.custom = {
								questionOrderId: this.questionOrderId,
								currentRole: this.role
							};
							this.orderInfo = res.result;
							//问诊类型
							this.inquiryType = res.result.commodityOrder.inquiryType;
							//问诊状态
							this.inquiryStatus = res.result.questionOrder.status;
							
							// 封装写病历需要的信息
							this.casesNeedInfo.patientId = res.result.patient.id
							this.casesNeedInfo.patientName = res.result.patient.patientName
							this.casesNeedInfo.patientSex = res.result.patient.sex
							this.casesNeedInfo.patientAge = res.result.patient.age
							this.casesNeedInfo.outpatientNumber = res.result.patient.outpatientNumber
							this.casesNeedInfo.visitTime = res.result.questionOrder.visitTime
							this.casesNeedInfo.orderId = res.result.commodityOrder.id
							this.casesNeedInfo.medRdNo = res.result.commodityOrder.outTradeNo
							
							// 封装病历夹需要的信息
							this.patientNeesInfo.patientId = res.result.patient.id
							this.patientNeesInfo.patientName = res.result.patient.patientName
							this.patientNeesInfo.patientSex = res.result.patient.sex
							this.patientNeesInfo.patientAge = res.result.patient.age
							this.patientNeesInfo.outpatientNumber = res.result.patient.outpatientNumber
		
							//封装患者信息
							let userInfo = {};
							userInfo.commodityOrder = {
								orderType: res.result.commodityOrder.orderType
							};
							userInfo.patient = {
								phone: res.result.patient.phone,
								patientName: res.result.patient.patientName,
								sex: res.result.patient.sex
							};
							userInfo.questionOrder = {
								drugQuestionReq: {
									allergy: res.result.questionOrder?.drugQuestionReq?.allergy,
									allergyText: res.result.questionOrder?.drugQuestionReq?.allergyText,
									birthStatus: res.result.questionOrder?.drugQuestionReq?.birthStatus,
									kidney: res.result.questionOrder?.drugQuestionReq?.kidney,
									liver: res.result.questionOrder?.drugQuestionReq?.liver
								},
								content: res.result.questionOrder.content,
								duration: res.result.questionOrder.duration,
								isLookHosp: res.result.questionOrder.isLookHosp,
								reportList: res.result.questionOrder.reportList,
								reexamination: res.result.questionOrder.reexamination
							};
		
							if (this.sendB && this.sendT && this.role == 1) {
								this.sendUserInfo(userInfo);
							}
						}
					} else {
						// uni.showToast({
						// 	title: res.message,
						// 	icon: 'none'
						// });
					}
				});
		},
		/**
		 * 发送患者信息 type=100
		 *
		 */
		sendUserInfo(data) {
			uni.showLoading({
				title: '加载中...'
			});
		
			let content = {
				type: 100,
				data: data
			};
			
			const TIM = app.globalData.TIM;
			const tim = app.globalData.tim;
			const message = tim.createCustomMessage({
				to: this.chatTo,
				conversationType: TIM.TYPES.CONV_C2C,
				payload: {
					data: JSON.stringify(content),
					description: '发送患者信息 type=100',
					extension: ''
				},
				cloudCustomData: JSON.stringify(this.custom)
			});
			tim.sendMessage(message)
				.then(imResponse => {
					uni.hideLoading();
					// 存储数据到store
					this.saveChatMessageListToStore(imResponse.data.message);
					// 滚动到底部
					this.scrollToBottom();
				})
				.catch(imError => {
					uni.hideLoading();
					// 判断错误类型，并做相应处理
					if (this.handleErrorAfterSend(imError)) {
						return;
					}
				});
		},
		
		/**
		 * 距离上一条消息是否超过两分钟
		 */
		judgeOverTwoMinute(time, messageArr) {
			let displayTimeHeader = '';
			let lastMessage = messageArr[messageArr.length - 1];
			if (lastMessage) {
				//拥有上一条消息
				let delta = time - lastMessage.time;
				if (delta > 2 * 60 * 1000) {
					//两分钟以上
					displayTimeHeader = calcTimeHeader(time * 1000);
				}
			} else {
				//没有上一条消息
				displayTimeHeader = calcTimeHeader(time * 1000);
			}
			return displayTimeHeader;
		},
		
		//初始化聊天
		initMessage() {
			//获取历史聊天记录
			if (this.rawMessageList['C2C' + this.accid]) {
				console.log('获取聊天历史记录', this.rawMessageList['C2C' + this.accid]);
				this.getHistoryMsgs();
			} else {
				this.setMessage();
				// 重新计算所有时间
				this.reCalcAllMessageTime();
			}
			
			setTimeout(() => {
				if (this.questionOrderId) {
					this.questionOrderDetail();
				}
				this.scrollToBottom();
			}, 600);
		},
		
		/**
		 * 收起所有输入框
		 */
		chatingWrapperClick(e) {
			this.foldInputArea();
		},
		/**
		 * 收起键盘
		 */
		foldInputArea() {
			this.focusFlag = false;
			this.emojiFlag = false;
			this.moreFlag = false;
		},
		/**
		 * 阻止事件冒泡空函数
		 */
		stopEventPropagation() {},
		/**
		 * 全屏播放视频
		 */
		requestFullScreenVideo(video) {
			let videoContext = uni.createVideoContext('videoEle');
		
			this.isVideoFullScreen = true;
			// this.videoSrc = video.url;
			this.videoSrc = video.videoUrl;
			this.videoContext;
		
			videoContext.requestFullScreen();
			videoContext.play();
		},
		/**
		 * 视频播放结束钩子
		 */
		videoEnded() {
			this.isVideoFullScreen = false;
			this.videoSrc = '';
		},
		/**
		 * 播放音频
		 */
		playAudio(audio) {
			uni.showToast({
				title: '播放中',
				icon: 'none',
				duration: 120 * 1000,
				mask: true
			});
		
			const audioContext = uni.createInnerAudioContext();
			if (audio.ext === 'mp3') {
				// 小程序发送的
				audioContext.src = audio.url;
			} else {
				audioContext.src = audio.url;
			}
			audioContext.play();
			audioContext.onPlay(() => {});
			audioContext.onEnded(() => {
				uni.hideToast();
			});
			audioContext.onError(res => {
				uni.showToast({
					title: res.errCode,
					icon: 'none'
				});
			});
		},
		/**
		 * 重新计算时间头
		 */
		reCalcAllMessageTime() {
			let tempArr = [...this.messageArr];
			if (tempArr.length == 0) return;
			// 计算时差
			tempArr.map((msg, index) => {
				if (index === 0) {
					msg['displayTimeHeader'] = calcTimeHeader(msg.time * 1000);
				} else {
					let delta = (msg.time - tempArr[index - 1].time) / (120 * 1000);
					if (delta > 1) {
						// 距离上一条，超过两分钟重新计算头部
						msg['displayTimeHeader'] = calcTimeHeader(msg.time * 1000);
					}
				}
			});
		
			this.messageArr = tempArr;
		},
		/**
		 * 切换发送文本类型
		 */
		switchSendType() {
			this.sendType = this.sendType == 0 ? 1 : 0;
			this.focusFlag = false;
			this.emojiFlag = false;
		},
		/**
		 * 文本框输入事件
		 */
		inputChange(e) {
			this.inputValue = e.detail.value;
		},
		/**
		 * 获取焦点
		 */
		inputFocus(e) {
			this.emojiFlag = false;
			this.focusFlag = true;
		},
		/**
		 * 失去焦点
		 */
		inputBlur() {
			this.focusFlag = false;
		},
		/**
		 * 键盘单击发送，发送文本
		 */
		inputSend(e) {
			this.sendRequest(e.detail.value);
		},
		/**
		 * emoji组件回调
		 */
		emojiCLick(val) {
			// 单击删除按钮，，删除emoji
			if (val == '[删除]') {
				let lastIndex = this.inputValue.lastIndexOf('[');
				if (lastIndex != -1) {
					this.inputValue = this.inputValue.slice(0, lastIndex);
				}
				return;
			}
			if (val[0] == '[') {
				// emoji
				this.inputValue = this.inputValue + val;
			} else {
				//大图
				this.sendBigEmoji(val);
			}
		},
		/**
		 * 发送大的emoji:实际上是type=3的自定义消息
		 * {"type":3,"data":{"catalog":"ajmd","chartlet":"ajmd010"}}
		 */
		sendBigEmoji(val) {
			uni.showLoading({
				title: '发送中...'
			});
		
			let catalog = '';
			if (val[0] === 'a') {
				catalog = 'ajmd';
			} else if (val[0] === 'x') {
				catalog = 'xxy';
			} else if (val[0] === 'l') {
				catalog = 'lt';
			}
			let content = {
				type: 3,
				data: {
					catalog,
					chartlet: val
				}
			};
			
			const TIM = app.globalData.TIM;
			const tim = app.globalData.tim;
			const message = tim.createCustomMessage({
				to: this.chatTo,
				conversationType: TIM.TYPES.CONV_C2C,
				payload: {
					data: JSON.stringify(content),
					description: '发送大的emoji:实际上是type=3的自定义消息',
					extension: ''
				},
				cloudCustomData: JSON.stringify(this.custom),
			});
			tim.sendMessage(message)
				.then(imResponse => {
					uni.hideLoading();
					// 存储数据到store
					this.saveChatMessageListToStore(imResponse.data.message);
							
					// 隐藏发送栏
					this.focusFlag = false;
					this.emojiFlag = false;
							
					this.moreFlag = false;
							
					// 滚动到底部
					this.scrollToBottom();
				})
				.catch(imError => {
					uni.hideLoading();
					// 判断错误类型，并做相应处理
					if (this.handleErrorAfterSend(imError)) {
						return;
					}
				});
		},
		/**
		 * emoji点击发送
		 */
		emojiSend(e) {
			let val = this.inputValue;
			this.sendRequest(val);
	
			this.emojiFlag = false;
		},
		/**
		 * 发送网络请求：发送文本消息(包括emoji)
		 */
		sendRequest(text) {
			JSON.stringify();
			app.globalData.tim.sendMessage(app.globalData.tim.createTextMessage({
				to: this.chatTo,
				conversationType: app.globalData.TIM.TYPES.CONV_C2C,
				payload: {
					text
				}
			})).then(imResponse => {
				// 发送成功
				if (imResponse.data) {
					// 存储数据到store
					this.saveChatMessageListToStore(imResponse.data.message);
					
					this.inputValue = '';
					this.focusFlag = false;
					
					// 滚动到底部
					this.scrollToBottom();	
				}
			}).catch(imError => {
				// 判断错误类型，并做相应处理
				if (this.handleErrorAfterSend(imError)) {
				   return;
				}
			})
		},
		/**
		 * 发送语音消息
		 */
		sendAudioMsg(res) {
			uni.showLoading({
				title: '发送中...'
			});
	
			const TIM = app.globalData.TIM;
			const tim = app.globalData.tim;
			const message = tim.createAudioMessage({
			    to: this.chatTo,
			    conversationType: TIM.TYPES.CONV_C2C,
			    payload: {
			      file: res
			    },
			    cloudCustomData: JSON.stringify(this.custom)
			});
			tim.sendMessage(message)
				.then(imResponse => {
					uni.hideLoading();
					// 存储数据到store
					this.saveChatMessageListToStore(imResponse.data.message);
							
					// 滚动到底部
					this.scrollToBottom();
				})
				.catch(imError => {
					uni.hideLoading();
					// 判断错误类型，并做相应处理
					if (this.handleErrorAfterSend(imError)) {
						return;
					}
				});
		},
		
		/**
		/**
		 * 统一发送消息后打回的错误信息
		 * 返回true表示有错误，false表示没错误
		 */
		handleErrorAfterSend(err) {
			console.warn('sendMessage error:', err);
			/*
			if (err) {
				if (err.code == 7101) {
					uni.showToast({
						title: '你已被对方拉黑',
						icon: 'none'
					});
				}
				console.log(err);
				return true;
			}
			return false;
			*/
		},
		/**
		 * 滚动页面到底部
		 */
		scrollToBottom() {
			uni.pageScrollTo({
				scrollTop: 999999,
				duration: 100
			});
		},
		// 保存数据到store
		saveChatMessageListToStore(msg, handledMsg) {
			this.$store.dispatch('txyIm/RawMessageList_Add_Msg', {
				msg
			});
			// this.setMessage()
		},
		/**
		 * 切出更多
		 */
		toggleMore() {
			this.moreFlag = !this.moreFlag;
			this.emojiFlag = false;
			this.focusFlag = false;
		},
		/**
		 * 切换出emoji键盘
		 */
		toggleEmoji() {
			this.sendType = 0;
			// this.focusFlag = this.emojiFlag ? true : false
			this.emojiFlag = !this.emojiFlag;
			this.moreFlag = false;
		},
		/**
		 * 手动模拟按钮长按，
		 */
		longPressStart() {
			this.recordClicked = true;
		
			setTimeout(() => {
				if (this.recordClicked == true) {
					this.executeRecord();
				}
			}, 350);
		},
		/**
		 * 语音按钮长按结束
		 */
		longPressEnd() {
			this.recordClicked = false;
		
			// 第一次授权，
			if (!this.recorderManager) {
				this.isLongPress = false;
		
				return;
			}
			if (this.isLongPress === true) {
				this.isLongPress = false;
		
				uni.hideToast();
				this.recorderManager.stop();
			}
		},
		/**
		 * 执行录音逻辑
		 */
		executeRecord() {
			this.isLongPress = true;
		
			uni.getSetting({
				success: res => {
					let recordAuth = res.authSetting['scope.record'];
					if (recordAuth == false) {
						//已申请过授权，但是用户拒绝
						uni.openSetting({
							success: res => {
								let recordAuth = res.authSetting['scope.record'];
								if (recordAuth == true) {
									uni.showToast({
										title: '授权成功',
										icon: 'success'
									});
								} else {
									uni.showToast({
										title: '请授权录音',
										icon: 'none'
									});
								}
		
								this.isLongPress = false;
							}
						});
					} else if (recordAuth == true) {
						// 用户已经同意授权
						this.startRecord();
					} else {
						// 第一次进来，未发起授权
						uni.authorize({
							scope: 'scope.record',
							success: () => {
								//授权成功
								uni.showToast({
									title: '授权成功',
									icon: 'success'
								});
							}
						});
					}
				},
				fail: err => {
					uni.showToast({
						title: '鉴权失败，请重试',
						icon: 'error'
					});
				}
			});
		},
		/**
		 * 开始录音
		 */
		startRecord() {
			uni.showToast({
				title: '开始录音',
				icon: 'none',
				duration: 120000
			});
		
			const recorderManager = this.recorderManager || uni.getRecorderManager();
			const options = {
				duration: 120 * 1000,
				format: 'mp3'
			};
			recorderManager.start(options);
		
			this.recorderManager = recorderManager;
		
			recorderManager.onStop(res => {
				if (res.duration < 2000) {
					uni.showToast({
						title: '录音时间太短',
						icon: 'none'
					});
				} else {
					this.sendAudioMsg(res);
				}
			});
		},
		/**
		 * 选择相册图片
		 */
		chooseImageToSend(e) {
			let that = this;
			let type = e.currentTarget.dataset.type;
			this.moreFlag = false;
			uni.chooseImage({
				sourceType: ['album'],
				success: res => {
					that.sendImageToNOS(res);
				}
			});
		},
		/**
		 * 选择拍摄视频或者照片
		 */
		chooseImageOrVideo() {
			let that = this;
			this.moreFlag = false;
			uni.showActionSheet({
				itemList: ['照相', '视频'],
				success: res => {
					if (res.tapIndex === 0) {
						// 相片
						uni.chooseImage({
							sourceType: ['camera'],
							success: res => {
								that.sendImageToNOS(res);
							}
						});
					} else if (res.tapIndex === 1) {
						// 视频
						uni.chooseVideo({
							sourceType: ['camera', 'album'],
							success: res => {
								if (res.duration > 60) {
									uni.showToast({
										title: '视频时长超过60s，请重新选择',
										icon: 'none'
									});
		
									return;
								}
								that.sendVideoToNos(res);
							}
						});
					}
				}
			});
		},
		/**
		 * 发送图片到nos
		 */
		sendImageToNOS(res) {
			uni.showLoading({
				title: '发送中...'
			});

			const TIM = app.globalData.TIM;
			const tim = app.globalData.tim;
			const message = tim.createImageMessage({
				to: this.chatTo,
				conversationType: TIM.TYPES.CONV_C2C,
				payload: { file: res },
				cloudCustomData: JSON.stringify(this.custom),
				onProgress: (event) => { 
					console.log('file uploading:', event) 
				}
			});
			tim.sendMessage(message)
				.then(imResponse => {
					uni.hideLoading();
					// 存储数据到store
					this.saveChatMessageListToStore(imResponse.data.message);
							
					// 滚动到底部
					this.scrollToBottom();
				})
				.catch(imError => {
					uni.hideLoading();
					// 判断错误类型，并做相应处理
					if (this.handleErrorAfterSend(imError)) {
						return;
					}
				});
		},
		/**
		 * 发送视频文件到nos
		 */
		sendVideoToNos(res) {
			uni.showLoading({
				title: '发送中...'
			});
			// {duration,errMsg,height,size,tempFilePath,width}
			
			const TIM = app.globalData.TIM;
			const tim = app.globalData.tim;
			const message = tim.createVideoMessage({
				to: this.chatTo,
				conversationType: TIM.TYPES.CONV_C2C,
				payload: { file: res },
				cloudCustomData: JSON.stringify(this.custom),
				onProgress: (event) => { 
					console.log('file uploading:', event) 
				}
			});
			tim.sendMessage(message)
				.then(imResponse => {
					uni.hideLoading();
					// 存储数据到store
					this.saveChatMessageListToStore(imResponse.data.message);
							
					// 滚动到底部
					this.scrollToBottom();
				})
				.catch(imError => {
					uni.hideLoading();
					// 判断错误类型，并做相应处理
					if (this.handleErrorAfterSend(imError)) {
						return;
					}
				});
		},
		//创建房间
		joinRoom() {
			uni.showLoading({
				title: '加载中'
			});
			setTimeout(() => {
				this.$api
					.createRoom({
						params: {
							inviteImToken: this.accid
						}
					})
					.then(res => {
						if (res.code == 200 && res.result.cidData.code == 200) {
							//进入房间
							const cid = res.result.cidData.cid;
							const channelName = res.result.roomNo
							let thisAccid;
							let nickName;
							if (this.role == 0) {
								thisAccid = imInfo.get().accid;
								nickName = this.orderInfo.patient.patientName;
							} else {
								thisAccid = this.doctorInfo.id;
								nickName = this.doctorInfo.doctorName;
							}
						
							const url = '/pages-txy-im/videoCall2/videoCall2';
							const queryParams = {
								originChannelName: channelName,
								channelName: channelName,
								uid: thisAccid,
								channelId: cid,
								token: '', // 如果是非安全模式，请传入空字符串
								nickName: nickName,
								openCamera: true,
								openMicrophone: true,
								resolution: 'FHD',
								audioQuality: 'high',
								videoWidth: 720,
								videoHeight: 1280,
								minBitrate: 1500,
								maxBitrate: 2000,
								debug: false,
								type:0
							};
							uni.setStorageSync("queryParams",JSON.stringify(queryParams))
							const finalUrl = Object.keys(queryParams).reduce((prev, cur) => {
								return `${prev}${prev === url ? '?' : '&'}${cur}=${queryParams[cur]}`;
							}, url);
			
							uni.navigateTo({ url: finalUrl });
						} else {
							uni.showToast({
								title: '视频通话失败',
								icon: 'none'
							});
						}
					});
			}, 2000);
		},
		//切换到页面问诊详情页面
		switchToOrderInfo(custom) {
			if (this.role == 1) {
				//医生查看患者问诊信息
				this.gotoRouter('/pages-doctor/orderInfo/orderInfo?id=' + custom.questionOrderId);
			} else {
				//患者查看患者问诊信息
				this.gotoRouter('/pages-order/inquiryOrderInfo/inquiryOrderInfo?id=' + custom.questionOrderId + '&showBtn=0');
			}
		},
		/**
		 * 切换到医生页面
		 */
		switchToPage(custom) {
			if (this.role == 0) {
				this.gotoRouter('/pages-hospital/doctorInfo/doctorInfo?id=' + this.chatTo);
			}
		},
		/**
		 * 展示编辑菜单
		 */
		showEditorMenu(message) {
			if (message.type === 'tip') {
				return;
			}
			let paraObj = {
				time: message.time,
				chatTo: this.chatTo,
				chatType: this.chatType
			};
		
			if (message.sendOrReceive === 'send') {
				// 自己消息
				uni.showActionSheet({
					itemList: ['删除', '撤回'],
					success: res => {
						switch (res.tapIndex) {
							case 0:
								this.deleteMessageRecord(message);
								break;
							case 1:
								uni.showActionSheet({
									itemList: ['确定'],
									itemColor: '#ff0000',
									success: res => {
										if (res.tapIndex === 0) {
											this.recallMessage(message);
										}
									}
								});
								break;
							default:
								break;
						}
					}
				});
			} else {
				// 对方消息
				uni.showActionSheet({
					itemList: ['删除'],
					success: res => {
						switch (res.tapIndex) {
							case 0:
								this.deleteMessageRecord(message);
								break;
							default:
								break;
						}
					}
				});
			}
		},
		/**
		 * 撤回消息
		 */
		recallMessage(message) {
			let sessionId = (this.chatType === 'p2p' ? 'C2C' : 'team-') + this.chatTo;
			let rawMessage = this.rawMessageList[sessionId][message.time];
			app.globalData.tim.revokeMessage(rawMessage)
				.then(imResponse => {
					// 撤回成功
					store.dispatch({
						type: 'RawMessageList_Recall_Msg',
						payload: msg
					});
					// 滚动到底部
					this.scrollToBottom();
				})
				.catch(imError => {
					// 撤回失败
					console.log(imError);
					uni.showToast({
						title: '消息已超过2分钟，不能撤回',
						icon: 'none'
					});
							
					return;
				});
		},
		/**
		 * 删除消息
		 * {displayTimeHeader,nodes,sendOrReceive,text,time,type}
		 */
		deleteMessageRecord(msg) {
			let sessionId = (this.chatType === 'p2p' ? 'C2C' : 'team-') + this.chatTo;
			// 从全局记录中删除
			store.dispatch({
				type: 'Delete_Single_MessageByAccount',
				payload: {
					sessionId: sessionId,
					time: msg.time
				}
			});
		},
		//发送处方给患者
		addUserRecipe() {
			this.recipeInfo.questionId = this.custom.questionOrderId || this.questionOrderId;
		
			this.$api
				.addUserRecipe({
					data: this.recipeInfo
				})
				.then(res => {
					if (res.code == 200) {
						let recipe = {
							questionId: this.recipeInfo.questionId,
							id: res.result,
							diagnose: this.recipeInfo.diagnose
						};
						this.sendRecipeInfo(recipe);
						this.setRecipeInfo(null);
					} else {
						uni.showToast({
							title: res.message,
							icon: 'none'
						});
					}
				});
		},
		/**
		 * 发送处方信息 type=101
		 *
		 */
		sendRecipeInfo(data) {
			uni.showLoading({
				title: '加载中...'
			});
		
			let content = {
				type: 101,
				data: data
			};
		
			const TIM = app.globalData.TIM;
			const tim = app.globalData.tim;
			const message = tim.createCustomMessage({
				to: this.chatTo,
				conversationType: TIM.TYPES.CONV_C2C,
				payload: {
					data: JSON.stringify(content),
					description: '发送处方信息 type=101',
					extension: ''
				},
				cloudCustomData: JSON.stringify(this.custom)
			});
			tim.sendMessage(message)
				.then(imResponse => {
					uni.hideLoading();
					// 存储数据到store
					this.saveChatMessageListToStore(imResponse.data.message);
					// 滚动到底部
					this.scrollToBottom();
				})
				.catch(imError => {
					uni.hideLoading();
					// 判断错误类型，并做相应处理
					if (this.handleErrorAfterSend(imError)) {
						return;
					}
				});
		},
	
		//问诊结算
		manualUpdateQuestionStatus() {
			uni.showModal({
				title: '确认要结束问诊吗？',
				success: res => {
					if (res.confirm) {
						this.$api
							.manualUpdateQuestionStatus({
								params: {
									id: this.questionOrderId
								}
							})
							.then(res => {
								this.TUICalling.destroyed()
								if (res.code == 200) {
									this.reLoad(this.options, false);
								} else {
									uni.showToast({
										title: res.message,
										icon: 'none'
									});
								}
							});
					}
				}
			});
		},
		
		// 调用视频通话
		videoCalling() {
			this.TUICalling.call({ userID: this.chatTo, type:2})
			/*
			uni.showLoading({
				title: '加载中...'
			});
					
			let content = {
				type: 1001,
				data: '发起视频通话'
			};
					
			const TIM = app.globalData.TIM;
			const tim = app.globalData.tim;
			const message = tim.createCustomMessage({
				to: this.chatTo,
				conversationType: TIM.TYPES.CONV_C2C,
				payload: {
					data: JSON.stringify(content),
					description: '发起视频通话',
					extension: ''
				},
				cloudCustomData: JSON.stringify(this.custom)
			});
			tim.sendMessage(message)
				.then(imResponse => {
					// 存储数据到store
					this.saveChatMessageListToStore(imResponse.data.message);
					setTimeout(() => {
						uni.hideLoading();
						// 滚动到底部
						this.scrollToBottom();
						// 跳转到通话页面
						uni.navigateTo({
							url: '/pages-txy-im/videoCall2/videoCall2?userID=' + this.chatTo + '&type=sender'
						})
					}, 2000);
				})
				.catch(imError => {
					uni.hideLoading();
					// 判断错误类型，并做相应处理
					if (this.handleErrorAfterSend(imError)) {
						return;
					}
				});
				*/
		},
		
		// 点击[开处方]：先写病历才能开处方
		goPharmacy () {
			this.$api.getCasesByOrderId({
				params: {
					orderId: this.casesNeedInfo.orderId
				}
			}).then(res => {
				if (res.code == 200 && res.result) {
					this.gotoRouter('/pages-doctor/mypharmacy/mypharmacy?from=chatRoom&activeTab=1&selectModel=1&diseasesName=' + res.result.diseasesName + '&diseasesCode=' + res.result.diseasesCode)
				} else {
					uni.showToast({
						title: '您还没有书写病历，请先书写病历',
						icon: 'none'
					});
				}
			}).catch((err)=>{
				uni.showToast({
					title: '接口异常',
					icon: 'none'
				});
			});
		},
		/**
		 * 文件上传到监管平台
		 */
		doUploadProcFile(res) {
			uni.uploadFile({
			  url: apiUrl + '/aos/hn/uploadProcFile',
			  filePath: res.tempFilePaths ? res.tempFilePaths[0] : res.tempFilePath,
			  name: 'file',
			  formData: {
				questionOrderId: this.questionOrderId
			  },
			  header: {
				'X-Access-Token': token.get() ? token.get() : ''
			  },
			  success: uploadFileRes => {
				console.log(uploadFileRes, '***********');
			  },
			  fail: uploadFileError => {
				console.log(uploadFileError, '???????????????');
			  }
			});
		},
		//查看处方
		gotoRouter2(url,id){
			this.$api
				.getUserRecipeDetail({
					params: {
						id: id
					}
				})
				.then(res => {
					if (res.code == 200) {
						if(res.result && res.result.status == 0){
							uni.showToast({
								title: '该处方未审核，不支持查看',
								icon: 'none'
							});
						}else{
							uni.navigateTo({
								url: url,
								success: res => {},
								fail: err => {}
							});
						}
					} else {
						uni.showToast({
							title: res.message,
							icon: 'none'
						});
					}
				});
		}
	}
};
</script>

<style lang="less">
@import './chatRoom.less';
</style>
